//
//  EmoticonView.swift
//  14-表情键盘
//
//  Created by 高伦展 on 2018/2/11.
//  Copyright © 2018年 glz. All rights reserved.
//

import UIKit

private let EmoticonViewCellId = "EmoticonViewCellId"

//MARK: - 表情键盘视图
class EmoticonView: UIView {
    
    //选中表情回调
    private var selectedEmoticonCallBack:(_ emoticon:Emoticon)->()

    //监听方法
    @objc private func clickItem(item:UIBarButtonItem){
        print("item:\(item.tag)")
        
        let indexPath = IndexPath(item: 0, section: item.tag)
        
        //滚动 collectionView
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }
    //构造函数
    init(selectedEomticon:@escaping (_ emoticon:Emoticon)->()) {
        selectedEmoticonCallBack = selectedEomticon
        
        var rect = UIScreen.main.bounds
        rect.size.height = 226
        
        super.init(frame: rect)
        
        setupUI()
        //backgroundColor = UIColor.red
        
        let indexPath = IndexPath(item: 0, section: 1)
        
        DispatchQueue.global().async{
            DispatchQueue.main.async {
                self.collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
            }
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var collectionView :UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmoticonLayout())
    private lazy var toolbar = UIToolbar()
    
    //表情包数组
    private lazy var packages = EmoticonManager.shareManager.packages
    
    //MARK - 表情布局（类中类-只允许被包含的类使用）
    private class EmoticonLayout:UICollectionViewFlowLayout{
        
        override func prepare() {
            super.prepare()
            
            let col:CGFloat = 7
            let row:CGFloat = 3
            
            let w = collectionView!.bounds.width / col
            let margin = CGFloat(Int((collectionView!.bounds.height - row * w) * 0.5))
            
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            scrollDirection = .horizontal
            collectionView?.isPagingEnabled = true
            collectionView?.bounces = false
            
        }
        
    }
    
}

extension EmoticonView{
    
    func setupUI(){
        addSubview(toolbar)
        addSubview(collectionView)
        
        //自动布局
        toolbar.snp.makeConstraints { (make) in
            make.bottom.equalTo(self.snp.bottom)
            make.left.equalTo(self.snp.left)
            make.right.equalTo(self.snp.right)
            make.height.equalTo(44)
        }
        
        collectionView.snp.makeConstraints { (make) in
            make.bottom.equalTo(toolbar.snp.top)
            make.left.equalTo(toolbar.snp.left)
            make.right.equalTo(toolbar.snp.right)
            make.top.equalTo(self.snp.top)
        }
        
        // 准备控件
        prepareToolbar()
        prepareCollectionView()
    }
    
    //准备工具栏
    private func prepareToolbar(){
        
        toolbar.tintColor = UIColor.darkGray
        
        //设置按钮内容
        var items = [UIBarButtonItem]()
        //toolbar 中，通常是一组功能相近的操作，只是操作的类型不同，通常利用tag来区分
        var index = 0
        for s in packages{
            items.append(UIBarButtonItem(title: s.group_name_cn, style: .plain, target: self, action:#selector(clickItem(item:))))
            items.last?.tag = index
            index += 1
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        
        items.removeLast()
        //设置items
        toolbar.items = items
        
    }

    //准备 collectionView
    private func prepareCollectionView() {
       
        collectionView.backgroundColor = UIColor.lightGray
        
        collectionView.register(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonViewCellId)
        
        collectionView.dataSource = self
        
        collectionView.delegate = self
    }
}

extension EmoticonView:UICollectionViewDataSource,UICollectionViewDelegate{
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let em = packages[indexPath.section].emoticons[indexPath.item]
        selectedEmoticonCallBack(em)
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonViewCellId, for: indexPath) as! EmoticonViewCell
        
        //cell.backgroundColor = (indexPath.item % 2) == 0 ? UIColor.red : UIColor.green
        
        //cell.emoticonButton.setTitle("\(indexPath.item)", for: .normal)
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        return cell
    }
}

//MARK: - 表情视图 Cell
class  EmoticonViewCell: UICollectionViewCell {
    ///表情模型
    var emoticon: Emoticon?{
        didSet{
            
            emoticonButton.setImage(UIImage(contentsOfFile:emoticon!.imagePath), for: .normal)
            emoticonButton.setTitle(emoticon?.emoji, for: .normal)
         
            if emoticon!.isRemoved{
                emoticonButton.setImage(UIImage(named:"compose_emotion_delete"), for: .normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emoticonButton)
        
        emoticonButton.backgroundColor = UIColor.white
        emoticonButton.setTitleColor(UIColor.black, for: .normal)
        emoticonButton.frame = bounds.insetBy(dx: 4, dy: 4) // CGRect.insetBy(bounds)(dx: 4, dy: 4)
        emoticonButton.titleLabel?.font = UIFont.systemFont(ofSize: 32)
        
        emoticonButton.isUserInteractionEnabled = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var emoticonButton: UIButton = UIButton()
}
